package com.beidouin.sensortest;

import android.util.Log;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;


public class UDPClient {
    private  int SERVER_PORT ;
    private DatagramSocket dSocket = null;
    private String msg;
    private  InetAddress pcadd;
    private InetSocketAddress inetSocketAddress = null;
    /**
     * @param msg
     */
    public UDPClient(String msg,InetAddress pcadd,int port) {
        super();
        this.msg = msg;
        this.pcadd = pcadd;
        this.SERVER_PORT = port;


    }
    /**
     * 发送信息到服务器
     */
    public String send() {
        StringBuilder sb = new StringBuilder();

        try {
                if(dSocket==null){
                dSocket = new DatagramSocket(null);
                dSocket.setReuseAddress(true);
                dSocket.bind(new InetSocketAddress(SERVER_PORT));
            }
           //dSocket = new DatagramSocket(SERVER_PORT); // 注意此处要先在配置文件里设置权限,否则会抛权限不足的异常
            sb.append("正在连接服务器...").append("/n");
            int msg_len = msg == null ? 0 : msg.getBytes("GBK").length;
            byte[] byt = new byte[0];
            try {
                byt = msg.getBytes("GBK");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            //pcadd = InetAddress.getByName("192.168.2.139");
            DatagramPacket dPacket = new DatagramPacket(byt, msg_len,pcadd, SERVER_PORT);
            try {
                dSocket.send(dPacket);
                sb.append("消息发送成功!").append("/n");
                Log.i("消息发送成功!", "消息发送成功!");
                dSocket.close();
                Log.i("overoer", "overover");
            } catch (IOException e) {
                e.printStackTrace();
                sb.append("消息发送失败.").append("/n");
            }
        } catch (SocketException e) {
            e.printStackTrace();
            sb.append("服务器连接失败.").append("/n");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return sb.toString();
    }
}
